import React, { useState, useCallback, useRef } from 'react';

import styles from './jsSwitchCssVar.less';

// 可以设置多套 js 配置，里面有主题相关数据，最终通过 js 设置到 dom element 的 properties 中
// css module 中相关类引用 css var，最终来自 js 设置的dom属性
// 参考 https://zhuanlan.zhihu.com/p/27347300 [译文]使自定义属性(CSS变量)更动态

interface ITheme {
  primaryColor: string;
  normalColor: string;
}

interface IThemes {
  [index: string]: ITheme;
}

const themes: IThemes = {
  a: {
    primaryColor: 'red',
    normalColor: 'orange',
  },
  b: {
    primaryColor: 'gray',
    normalColor: 'silver',
  },
};

const options = Object.entries(themes);
const optionsEl = options.map(([n, v]) => (
  <option key={n} value={n}>
    {n}
  </option>
));
const selectEl = <select>{optionsEl}</select>;

function setTheme(element: any, theme: ITheme) {
  Object.entries(theme).forEach(([k, v]) => {
    console.log(`--${k}`, v);
    element.style.setProperty(`--${k}`, v);
  });
}

export default function() {
  const ref = useRef(null);
  const [selectedThemeName, selectTheme] = useState('');
  const onSelectTheme = useCallback(event => {
    selectTheme(event.target.value);
    const theme = themes[event.target.value];
    console.log(event.target, theme, ref.current);
    if (!theme || !ref.current) return;
    setTheme(ref.current, theme);
    // ref.current.style.setProperty('--primaryColor', theme.primaryColor);
    // ref.current.style.setProperty('--normalColor', theme.normalColor);
  }, []);
  return (
    <div ref={ref} className={styles.normal}>
      <h1 className={styles.h1}>Page jsSwitchCssVar</h1>
      <div>selectedThemeName: {selectedThemeName}</div>
      <select onChange={onSelectTheme}>{optionsEl}</select>
    </div>
  );
}
